from fastapi import APIRouter, Depends, Request
from starlette.responses import HTMLResponse

from applications.common.render_template import templates
from applications.common.user_manager import permission_depends
from applications.utils.http import table_api, PageResponse
from applications.models import OperationLog, LoginLog
from applications.models.admin_log import OperationLogOut, LogOutSchema
from applications.schemas.admin_log import LogQueryParams

router = APIRouter(prefix="/log", tags=["系统管理-日志管理"])


# 日志管理
@router.get(
    "/",
    dependencies=[Depends(permission_depends("system:log:main"))],
    response_class=HTMLResponse,
    include_in_schema=False,
)
async def index(request: Request):
    return templates.TemplateResponse("system/admin_log/main.html", {"request": request})


# 登录日志
@router.get(
    "/loginLog",
    dependencies=[Depends(permission_depends("system:log:main"))],
    summary="获取登录日志",
    response_model=PageResponse[LogOutSchema],
)
async def login_log(params: LogQueryParams = Depends()):
    query = LoginLog.all().order_by("-create_time")
    count = await query.count()
    logs = await query.offset((params.page - 1) * params.limit).limit(params.limit)
    return table_api(data=logs, count=count)


# 操作日志
@router.get(
    "/operateLog",
    dependencies=[Depends(permission_depends("system:log:main"))],
    summary="获取操作日志",
    response_model=PageResponse[OperationLogOut],
)
async def operate_log(params: LogQueryParams = Depends()):
    query = OperationLog.all().order_by("-create_time")
    count = await query.count()
    logs = await query.offset((params.page - 1) * params.limit).limit(params.limit)
    return table_api(data=logs, count=count)
